import {HTTP} from '../utils/http.js'
class ClassicModel extends HTTP{
  getLatest(sCallBack){
    this.request({
      url: 'classic/latest',
      success: (res) => {
        sCallBack(res);
        this._setLatestIndex(res.index);
        //因为最新一期的数据不确定，所以直接写入缓存
        let key = this._getKey(res.index);
        wx.setStorageSync(key,res);
      }
    });
  }

  getClassic(index, nextOrPrevious, sCallBack){
    // 缓存中寻找
    let key = nextOrPrevious=='next'?this._getKey(index+1):this._getKey(index-1);
    let classic = wx.getStorageSync(key);
    if(!classic){// 缓存中没有数据
      this.request({
        url: `classic/${index}/${nextOrPrevious}`,// 模板字符串
        success: (res) => {
          // 缓存没有数据就把当前请求到的数据写入缓存中
          wx.setStorageSync(this._getKey(res.index),res);
          sCallBack(res);
        }
      });
    }else {
      //缓存中有数据的情况，就不用再请求数据获取res了
      sCallBack(classic)
    }
  }

  isFirst(index){
    return index == 1;
  }

  isLatest(index){
    let latestIndex = this._getLatestIndex();
    return index == latestIndex;
  }

  // 缓存最新一期的index
  _setLatestIndex(index){
    wx.setStorageSync('latest',index);
  }

  // 获取缓存数据的index
  _getLatestIndex(){
    let index = wx.getStorageSync('latest');
    return index;
  }

  _getKey(index) {
    let key = 'classic-' + index;
    return key;
  }

  /**
   * 为my页面获取我喜欢的期刊
   * @param success
   */
  getMyFavor(success){
    const params = {
      url: 'classic/favor',
      success: success
    };
    this.request(params);
  }

}
export {ClassicModel}